#include <dirent.h>
#include <stdio.h>
#include <sstream>
#include "assert_helper.h"
#include "charset_convert.h"
#include "file_helper.h"

namespace utility {
bool	is_file_exist(const char * file)
{
	IF_NULL_RETURN_VALUE(file, false);
	return access(file, F_OK) == 0 ? true : false;
}

bool	is_file_exist(const std::string & file)
{
	return is_file_exist(file.c_str());
}

bool
get_pe_file_version(const char *path, int & major, int & minor)
{
   IF_NULL_RETURN_VALUE(path, false);
   char   sample[] = "ERSION_INFO";
   TCHAR temp = 0;
   int  i = 0;
   char   flag = 0;
   FILE  *PE;

   PE = fopen(path, "rb");
   if (NULL != PE)
   {
      fread(&temp, sizeof(TCHAR), 1, PE);
      if (temp == 0X5A4D) /* 检查是否“PE”标志 */
      {
         while (!feof(PE))
         {
            fread(&temp, sizeof(TCHAR), 1, PE);
       
            if (temp == (TCHAR)'V')
            {
               flag = 1;
               for (i = 0; i < strlen(sample); ++i)
               {
                  fread(&temp, sizeof(TCHAR), 1, PE);
                  if ( temp != (int)(sample[i]) )
                  {
                     flag = 0;
                     break;
                  }
               }
            }
     
            if (0 != flag)
            {
               fseek(PE, 0X14L, SEEK_CUR);
               fread(&major, sizeof(int), 1, PE);
               fread(&minor, sizeof(int), 1, PE);
               fclose(PE);
               return true;
            }
         }         
      }
      fclose(PE);
   }
   return false;
}

std::string 
get_pe_file_version(const char *path)
{
   IF_NULL_RETURN_VALUE(path, false);
   int major = 0, minor = 0;
   if (get_pe_file_version(path, major, minor)) {
   	std::stringstream ver;
   	ver << static_cast<unsigned short>(major >> 16) << "." <<
   	static_cast<unsigned short>(major & 0XFFFF) << "." <<
   	static_cast<unsigned short>(minor >> 16) << "." <<
   	static_cast<unsigned short>(minor & 0XFFFF);
		return ver.str();
	}
	return "";
}

}
